﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using NewFormatProject.Infrastructure.EFCore;
using NewFormatProject.Server.Interfaces;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace NewFormatProject.Api.Admin
{
    public class GlobalErrorHandler
    {
        private readonly RequestDelegate _next;
        private readonly IConfiguration _configuration;

        public GlobalErrorHandler(RequestDelegate next, IConfiguration configuration)
        {
            _next = next;
            _configuration = configuration;
        }

        public async Task InvokeAsync(HttpContext context, IErrorLogServer errorLogServer)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                try
                {
                    // 获取请求参数
                    string requestParames = "";
                    foreach (var key in context.Request.Query.Keys)
                    {
                        requestParames += key + "=" + context.Request.Query[key] + "&";
                    }

                    // 如果需要获取表单数据或 JSON 数据
                    if (context.Request.HasFormContentType)
                    {
                        var formCollection = context.Request.Form;
                        // 使用 formCollection 获取表单数据
                        foreach (var key in formCollection.Keys)
                        {
                            requestParames += key + "=" + formCollection[key] + "&";
                        }
                    }
                    else if (context.Request.ContentType.StartsWith("application/json"))
                    {
                        // 读取 JSON 请求体
                        var requestBody = context.Request.Body;
                        requestBody.Position = 0;
                        using (var reader = new StreamReader(requestBody))
                        {
                            var bodyText = await reader.ReadToEndAsync();
                            requestParames += bodyText;
                        }
                    }
                    string url = context.Request.Scheme + "://" + context.Request.Host + context.Request.Path;
                    // 写入数据库
                    try
                    {
                       await errorLogServer.Add(new SysErrorLogs
                        {
                            ElParams = requestParames,
                            ElErrorTime = DateTime.Now,
                            ElMessage=ex.Message,
                            ElUrl=url,
                            ElStackTrack=ex.StackTrace
                        });
                    }
                    catch
                    {

                    }
                    // 写入文件
                    try
                    {
                        string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "Logs","Errors", DateTime.Now.ToLongDateString() + ".txt");

                        // 获取文件所在的目录路径
                        string directoryPath = Path.GetDirectoryName(filePath);

                        // 检查目录是否存在，如果不存在，则创建它
                        if (!Directory.Exists(directoryPath))
                        {
                            Directory.CreateDirectory(directoryPath);
                        }

                        // 检查文件是否存在，如果不存在，则创建它
                        if (!File.Exists(filePath))
                        {
                            File.Create(filePath).Close(); // 创建文件并关闭流
                        }
                        string fileText = File.ReadAllText(filePath);
                        File.WriteAllText(filePath, "错误消息：" + ex.Message + "\r\n" +
                            "URL:" + url + "\r\n" +
                            "Params:" + requestParames + "\r\n" +
                            "堆栈跟踪：" + ex.StackTrace + "\r\n" +
                            "创建时间：" + DateTime.Now.ToLocalTime() + "\r\n" +
                            "\r\n\r\n" + fileText);
                        context.Response.StatusCode = 500;
                        context.Response.ContentType = "text/plain; charset=utf-8";
                        await context.Response.WriteAsync(ex.Message);
                    }
                    catch
                    {
                        // 记录错误失败
                    }
                }
                catch
                {

                }
            }
        }
    }
}
